import { useEffect, useRef, useState } from 'react'
import { ModalForm, ProFormText, ProFormDigit } from '@ant-design/pro-components'
import type { ProFormInstance } from '@ant-design/pro-components'
import { message } from 'antd'
import { ShowEditProductFnc, EditProductFnc } from '@/services/goods'
import { itemType, propType } from './type'


const EditBox = ({isModalOpen, openBox, goodsID, actionRef}: propType) => { 
  const formRef: any = useRef<ProFormInstance>();
  const [messageApi, contextHolder] = message.useMessage()
  // 用于做比较的form
  const [formObj, setFormObj] = useState({});  

  // 打开编辑盒子
  const init = async () => {
    if(String(goodsID) !== '') {
      const res = await ShowEditProductFnc(parseInt(goodsID))
      if(res.meta.status === 200) {
        formRef.current.setFieldsValue({
          goods_name: res.data.goods_name,
          goods_price: res.data.goods_price,
          goods_number: res.data.goods_number,
          goods_weight: res.data.goods_weight
        })
        setFormObj(formRef.current.getFieldsValue())
      }
    }
  }
  useEffect(() => { init() }, [goodsID])

  const onFinish = async (val: itemType) => {
    if(JSON.stringify(formObj) === JSON.stringify(val)) {
        openBox(false)
    } else {
      const res =  await EditProductFnc(parseInt(goodsID),val)
      if(res.meta.status === 200) {
        messageApi.success('更新成功', 1.5, () => {
          openBox(false)
          actionRef.current?.reload();
        })
      }
    }
  }  
  return (
    <>
     {contextHolder} 
     <ModalForm
      title='修改商品'
      formRef={formRef}
      width={500}
      layout="horizontal"
      labelCol={{ span: 4 }}
      open={isModalOpen}
      onFinish={async (val: itemType) => onFinish(val)}
      modalProps={{ onCancel: () => openBox(false) }}
    >
      <ProFormText
        name="goods_name"
        label="商品名称"
        rules={[
          { required: true, message: '请输入商品名称' },
          { min: 3, max: 100, message: '长度在3-100个字符' },
        ]}
      />
        <ProFormDigit
          name="goods_price"
          label="商品价格"
          rules={[
            { required: true, message: '请输入商品价格' }
          ]}
        />
      <ProFormDigit
        name="goods_number"
        label="商品数量"
        rules={[{ required: true, message: '请输入数量' }]}
      />
      <ProFormDigit
        name="goods_weight"
        label="商品重量"
        rules={[{ required: true, message: '请输入重量' }]}
      />
     </ModalForm>
    </>
  )  
}

export default EditBox